
/* some code *stolen* from the great book generative gestaltung
 * http://www.generative-gestaltung.de
 * 
 * 
 * 
 */

package wpRelationsSandbox;

import generativedesign.GenerativeDesign;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;

import processing.core.PApplet;
import processing.xml.XMLElement;

public class wArticle {
	protected static String QUERY_BASE_0 = "http://en.wikipedia.org/w/api.php?format=xml&action=query&prop=categories&titles=";
	protected static String QUERY_BASE_1 = "&cllimit=500&plnamespace=0&redirects";
	protected static String QUERY_BASE_2 ="http://en.wikipedia.org/w/api.php?format=xml&action=query&list=categorymembers&cmtype=page|subcat&cmprop=type|title&cmtitle=";  
	protected static String QUERY_BASE_3 = "&cmlimit=500&redirects";

	protected String title;
	private boolean isAPerson;
	protected float mass;
	protected PApplet parent;
	protected XMLElement linksXML;
	protected ArrayList categories = new ArrayList();
	boolean availableLinksLoaded; 

	public wArticle() {
		
	}
	
	public wArticle(PApplet theParent, String theTitle) {
		parent = theParent;
		title = theTitle;
		setTitle();
	
	}
	
	
	private void setTitle(){
		String url = encodeURL(QUERY_BASE_0+title+QUERY_BASE_1);
		linksXML = GenerativeDesign.loadXMLAsync(parent, url); //starts the loading process with the url;  
		availableLinksLoaded = false; // starts the surveillance modus >> inLoaderLoop ;
	}
	
	

	
	
	private boolean isItAPerson() {
		boolean answer = false; 
		
	    Iterator itr = categories.iterator();
	      while(itr.hasNext()) {
		    	String s = itr.next().toString();
		    	if (s.contains("deaths") || s.contains("births")) {
		    		answer = true;
		    		 System.out.println(answer);
		    		return answer;
		    	}
		    }
	      System.out.println(answer);
	      return answer;
	      
	}
	
	
void loaderLoop(){ 
			// loop is trickered the whole time by main draw();   
			//System.out.println("looping"); 
		 
		 if (!availableLinksLoaded) 	{ //availableLinksLoaded == false when setID was setted; 
			if (linksXML.hasChildren()==false){ //when GenerativeDesign.loadXMLAsync==flase than its still loading; 
				System.out.println(" .... loading .... "); 
		 	}
			else // linksXML.hasChildren()==true; GenerativeDesign.loadXMLAsync has loaded everything and returns hasChildren == true;
		      	{ 
		    	XMLElement[] children = linksXML.getChildren("query/pages/page/categories/cl"); 
		    	for (int i = 1; i < children.length; i++) 
		    	{
			        String title = children[i].getStringAttribute("title");
			        categories.add(title); 
			       // System.out.println(title); 
			        
		         }
				 System.out.println("// allLoaded");
				 availableLinksLoaded = true; //stop the whole surveillance modus; 
				 isItAPerson(); //check in isItAPerson, if the categories-array-list now contains death/or birth
				 
		      }
			
		 	}
		 
		 
}
	
	
	
	
	
	
	public String getTitle() {
		return title;
	}
	
	public boolean checkPerson() {
		return isAPerson;
	}
	
	// function encodeURL based on a post on the processing discourse pages
	// posted by PhiLho on May 28th, 2008
	//
	// converts special chars in a string to be suitable for a url
	public String encodeURL(String url) {

	  // Use URI to encode low Ascii characters depending on context of various parts
	  // For some reason, uri = new URI(url) chokes on space, so we have to split the URL
	  String scheme = null;  // http, ftp, etc.
	  String ssp = null; // scheme-specific part
	  String fragment = null; // #anchor for example
	  int colonPos = url.indexOf(":");
	  if (colonPos < 0) return "Not an URL";
	  scheme = url.substring(0, colonPos);
	  ssp = url.substring(colonPos + 1);
	  int fragPos = ssp.lastIndexOf("#");
	  if (fragPos >= 0) {
	    // Won't work if there is no real anchor/fragment
	    // but this char is part of one parameter of the query,
	    // but it is a bit unlikely...
	    // That's probably why Java doesn't want to do it automatically,
	    // it must be disambiguated manually
	    fragment = ssp.substring(fragPos + 1);
	    ssp = ssp.substring(0, fragPos);
	  }

	  URI uri = null;
	  try {
	    uri = new URI(scheme, ssp, fragment);
	  } 
	  catch (URISyntaxException use) { 
	    return use.toString(); 
	  }
	  String encodedURL1 = null;
	  try {
	    encodedURL1 = uri.toURL().toString();
	  } 
	  catch (MalformedURLException mue) { 
	    return mue.toString(); 
	  }
	  // Here, we still have Unicode chars unchanged

	  byte[] utf8 = null;
	  // Convert whole string to UTF-8 at once: low Ascii (below 0x80) is unchanged, other stuff is converted
	  // to UTF-8, which always have the high bit set.
	  try {
	    utf8 = encodedURL1.getBytes("UTF-8");
	  } 
	  catch (UnsupportedEncodingException uee) { 
	    return uee.toString(); 
	  }

	  StringBuffer encodedURL = new StringBuffer();

	  byte[] conv = new byte[1];
	  for (int i = 0; i < utf8.length; i++) {
	    // Beyond Ascii: high bit is set, hence negative byte
	    if (utf8[i] < 0) {
	      encodedURL.append("%" + Integer.toString(256 + (int)utf8[i], 16));
	    }
	    else {
	      conv[0] = utf8[i];
	      try {
	        encodedURL.append(new String(conv, "ASCII")); // Convert back to Ascii
	      } 
	      catch (UnsupportedEncodingException uee) { 
	        return uee.toString(); 
	      }
	    }
	  }

	  return encodedURL.toString();
	}

	
}
